package com.luck.global;

import cn.hutool.core.collection.CollUtil;
import cn.hutool.core.exceptions.ValidateException;
import cn.hutool.core.util.ObjectUtil;
import cn.hutool.jwt.JWTValidator;
import cn.hutool.jwt.signers.JWTSignerUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.gateway.filter.GatewayFilterChain;
import org.springframework.cloud.gateway.filter.GlobalFilter;
import org.springframework.core.Ordered;
import org.springframework.http.HttpStatus;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.http.server.reactive.ServerHttpResponse;
import org.springframework.stereotype.Component;
import org.springframework.web.server.ServerWebExchange;
import reactor.core.publisher.Mono;

import java.net.URI;
import java.util.ArrayList;
import java.util.List;

@Slf4j
//@Component
public class TokenGlobalFilter implements GlobalFilter , Ordered {
    @Value("${com.lk.smart.tokenx.key}")
    private String tokenKey;

    private static List<String> whiteList = CollUtil.newArrayList("/api/user/login", "/api/user/register");
    @Override
    public Mono<Void> filter(ServerWebExchange exchange, GatewayFilterChain chain) {
        ServerHttpRequest request = exchange.getRequest();
        ServerHttpResponse response = exchange.getResponse();
        URI uri = request.getURI();
        if (whiteList.contains(uri.getPath())){
            return chain.filter(exchange);
        }
        String token = request.getHeaders().getFirst("token");
        if (ObjectUtil.isEmpty(token)){
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }
        try {
            JWTValidator.of(token)
                    .validateAlgorithm(JWTSignerUtil.hs256(tokenKey.getBytes()))
                    .validateDate();
        }catch (ValidateException ex){
            log.error("token验证失败",ex);
            response.setStatusCode(HttpStatus.UNAUTHORIZED);
            return response.setComplete();
        }


        return chain.filter(exchange);
    }

    @Override
    public int getOrder() {
        return 1;
    }
}
